# apps/accounts/tests.py
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status

User = get_user_model()

class UserProfileViewTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username='testuser',
            password='testpass123',
            email='test@example.com',
            phone='13800138000',
            bio='这是一个测试描述',
            points=50,
            user_type='consumer',
            city='上海市',
            district='浦东新区',
        )
        
        self.client = APIClient()
        self.client.force_authenticate(user=self.user)
        
        # 根据User模型调整测试数据
        self.test_data = {
            'email': 'new@example.com',
            'phone': '13900139000',
            'bio': '更新后的测试描述',
            'points': 100,
            'city': '北京市',
            'district': '朝阳区',
        }

    def test_retrieve_user_profile(self):
        url = reverse('accounts:profile')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        
        # 验证User模型的字段
        self.assertIn('username', response.data)
        self.assertIn('email', response.data)
        self.assertIn('phone', response.data)
        self.assertIn('bio', response.data)
        self.assertIn('points', response.data)

    def test_update_user_profile(self):
        url = reverse('accounts:profile')
        response = self.client.put(url, data=self.test_data, format='json')
        
        print(f"响应状态码: {response.status_code}")
        print(f"响应内容: {response.content}")
        
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        
        # 验证更新后的数据
        self.assertEqual(response.data['email'], self.test_data['email'])
        self.assertEqual(response.data['phone'], self.test_data['phone'])
        self.assertEqual(response.data['bio'], self.test_data['bio'])
        self.assertEqual(response.data['points'], self.test_data['points'])

    def test_unauthenticated_access(self):
        self.client.logout()
        url = reverse('accounts:profile')
        response = self.client.get(url)
        
        # 403或401都可以接受（取决于权限实现）
        self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])